package com.news.servlet;

import com.news.model.News;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    private static final int SORT_ID = 1; // 首页新闻
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            
            // 获取各类新闻数据
            List<News> recommendNews = newsService.getRecommendNews(SORT_ID);
            List<News> focusNews = newsService.getFocusNews(SORT_ID);
            List<News> deepNews = newsService.getDeepNews(SORT_ID);
            
            if (recommendNews == null || focusNews == null || deepNews == null) {
                request.setAttribute("message", "新闻加载失败，请稍后重试");
            }
            
            // 将数据存入request域
            request.setAttribute("recommendNews", recommendNews);
            request.setAttribute("focusNews", focusNews);
            request.setAttribute("deepNews", deepNews);
            
            // 在转发前添加
            request.setAttribute("currentPage", "index");
            
            // 转发到index.jsp
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception e) {
            request.setAttribute("message", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
} 